﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.HVAC;
using YArchitech.MEP;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class RiserPipeCorrect : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				UIApplication application = commandData.Application;
				Autodesk.Revit.ApplicationServices.Application application2 = application.Application;
				Document document = application.ActiveUIDocument.Document;
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				AuxiliaryFrameOperation afOperation = new AuxiliaryFrameOperation();
				RiserPipeOperation riserPipeOperation = new RiserPipeOperation();
				ISelectionFilter riserPipeFilter = new RiserPipeFilter();
				Selection selection = activeUIDocument.Selection;
				double zStart = 0.0;
				double zEnd = 0.0;
				PipeType pipeType = null;
				PipingSystemType pipingSystemType = null;
				string paraDiameter = "0";
				Transaction transaction2 = new Transaction(document, "添加共享参数");
				transaction2.Start();
				MarkOperation markOperation = new MarkOperation();
				markOperation.AddAllShareParametes(application);
				transaction2.Commit();
				markOperation.SetActiveDocAllLoadedTags(document);
				List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(1);
				if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					transaction = new Transaction(document, "水管立管编辑");
					transaction.Start();
					for (;;)
					{
						try
						{
							Pipe pipe = this.GetPipe(selection, document, riserPipeFilter);
							FormReiseDrawVerticalPipe formReiseDrawVerticalPipe = new FormReiseDrawVerticalPipe(document, riserPipeOperation.GetLevelUp(document), riserPipeOperation.GetPipeType(document), riserPipeOperation.GetPipingSystemType(document), pipe);
							if (DialogResult.OK == formReiseDrawVerticalPipe.ShowDialog())
							{
								riserPipeOperation.SetParament(ref zStart, ref zEnd, ref pipeType, ref pipingSystemType, ref paraDiameter, formReiseDrawVerticalPipe);
								new HYCreatePipeHelper().CorrectRiserPipe(pipe, zStart, zEnd, document, pipeType, paraDiameter, pipingSystemType, "");
								this.MarkCorrect(afOperation, pipe, document, formReiseDrawVerticalPipe, riserPipeOperation, activeUIDocument, application);
								continue;
							}
						}
						catch (Autodesk.Revit.Exceptions.OperationCanceledException)
						{
						}
						break;
					}
					transaction.Commit();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				this.EndTransation(transaction, false);
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				this.EndTransation(transaction, true);
			}
			return result;
		}

		private Pipe GetPipe(Selection selection, Document doc, ISelectionFilter riserPipeFilter)
		{
			RevitVersionFuncs.ClearSelection(selection);
			Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, riserPipeFilter, "请选择要编辑的水管立管");
			Element element = doc.GetElement(reference);
			RevitVersionFuncs.AddToSelection(selection, element);
			return (Pipe)element;
		}

		private void EndTransation(Transaction tran, bool beSure)
		{
			if (tran != null)
			{
				TransactionStatus status = tran.GetStatus();
				if ((int)status == 1)
				{
					if (beSure)
					{
						tran.Commit();
						return;
					}
					tran.RollBack();
					return;
				}
				else if ((int)status == 5)
				{
					tran.RollBack();
				}
			}
		}

		private bool MarkCorrect(AuxiliaryFrameOperation afOperation, Pipe pipe, Document doc, FormReiseDrawVerticalPipe drawPipeForm, RiserPipeOperation rpOperation, UIDocument uidoc, UIApplication uiApp)
		{
			string text = afOperation.ReadAuxiliaryFrameStrIds(pipe);
			if (!string.IsNullOrEmpty(text) && doc.GetElementById(new ElementId(Convert.ToInt32(text))) != null)
			{
				doc.DeleteElement(doc.GetElementById(new ElementId(Convert.ToInt32(text))));
			}
			doc.Regenerate();
			if (drawPipeForm.isAuxiliaryFrame)
			{
				text = rpOperation.CreateAuxiliaryFrame(drawPipeForm.isAuxiliaryFrame, uidoc, ((LocationCurve)pipe.Location).Curve.GetEndPoint(0), drawPipeForm.length, drawPipeForm.angle, afOperation);
			}
			else
			{
				text = string.Empty;
				drawPipeForm.length = 0.0;
			}
			afOperation.SetAuxiliaryFramePipe(doc, pipe, drawPipeForm.isAuxiliaryFrame, drawPipeForm.length, text);
			if (!string.IsNullOrEmpty(afOperation.ReadAuxiliaryFrameGroupId(pipe)))
			{
				string str = string.Empty;
				string str2 = string.Empty;
				if (drawPipeForm.cbDistrict.Checked)
				{
					if (drawPipeForm.hyTextBox3.Text == "" || !Regex.IsMatch(drawPipeForm.hyTextBox3.Text, "^[A-Za-z]+$"))
					{
						MessageBox.Show("区号不能为空且必须是英文字母", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
						drawPipeForm.hyTextBox3.Focus();
						return false;
					}
					str = drawPipeForm.hyTextBox3.Text + "-";
				}
				if (drawPipeForm.cbBuild.Checked)
				{
					if (drawPipeForm.hyTextBox4.Text == "")
					{
						MessageBox.Show("楼号不能为空", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
						drawPipeForm.hyTextBox4.Focus();
						return false;
					}
					str2 = drawPipeForm.hyTextBox4.Text + "-";
				}
				string text2 = str + str2;
				string text3 = drawPipeForm.hyTextBox2.Text;
				Parameter parameter = pipe.GetParameter("区号楼号");
				if (parameter != null)
				{
					parameter.Set(text2);
					parameter = pipe.GetParameter("立管编号");
					parameter.Set(text3);
				}
				else
				{
					MarkRiserPipeUtility.SetRiserPipeParameters(uiApp, pipe, text2, text3, drawPipeForm.rbCuston.Checked, false);
				}
			}
			else
			{
				rpOperation.SetMark(pipe, uidoc, drawPipeForm, uiApp, afOperation);
			}
			return true;
		}
	}
}
